package cn.tjad.tjad2.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.cache.SPCacheManager;
import cn.tjad.tjad2.listener.IImageToStringCallback;

public class Tools {

    public static void showToast(String text) {
        Toast.makeText(TjadApplication.getInstance(), text, Toast.LENGTH_LONG).show();
    }

    public static void showToast(int resId) {
        Toast.makeText(TjadApplication.getInstance(), resId, Toast.LENGTH_LONG).show();
    }

    public static void showSnackBar(View anchor, String text) {
        Snackbar.make(anchor, text, Snackbar.LENGTH_LONG).show();
    }

    public static int getProjectId() {
        if (TjadApplication.getInstance().getSession() != null) {
            return TjadApplication.getInstance().getSession().getProjectId();
        }
        return -1;
    }

    public static String getDisplayedFileSize(long bytes) {
        String result = "";
        DecimalFormat format = new DecimalFormat("#.00");
        if (bytes < 1024) {
            result = bytes + "Bytes";
        } else if (bytes < 1024 * 1024) {
            result = format.format(bytes / 1024.0) + "KB";
        } else if (bytes < 1024 * 1024 * 1024) {
            result = format.format(bytes / (1024.0 * 1024)) + "MB";
        } else if (bytes < 1024 * 1024 * 1024 * 1024) {
            result = format.format(bytes / (1024.0 * 1024 * 1024)) + "GB";
        } else  {
            result = format.format(bytes / (1024.0 * 1024 * 1024 * 1024)) + "TB";
        }
        return result;
    }

    public static long getFileSize(File file) {
        if (file == null || !file.exists()) {
            return 0;
        }
        long total = 0;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                for (File f : files) {
                    total += getFileSize(f);
                }
            }
        } else {
            total = file.length();
        }
        return total;
    }

    public static String getFileSubfix(String name) {
        if (name == null) {
            return null;
        }
        int dotIndex = name.lastIndexOf(".");
        if (!name.endsWith(".")) {
            String subfix = name.substring(dotIndex + 1);
            return subfix;
        } else {
            return "";
        }
    }

    public static boolean isImageFile(String fileName) {
        String subfix = getFileSubfix(fileName);
        return  "jpg".equalsIgnoreCase(subfix)
                || "jpeg".equalsIgnoreCase(subfix)
                || "png".equalsIgnoreCase(subfix)
                || "gif".equalsIgnoreCase(subfix);
    }

    public static boolean isGifFile(String fileName) {
        String subfix = getFileSubfix(fileName);
        return "gif".equalsIgnoreCase(subfix);
    }

    public static int getFileIcon(String subfix) {
        int icon = R.drawable.file_icon_unknown;
        if ("rvt".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_rvt;
        } else if ("dwg".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_dwg;
        } else if ("pdf".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_pdf;
        } else if ("jpg".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_jpg;
        } else if ("png".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_png;
        }
        return icon;
    }

    public static int getFileSmallIcon(String subfix) {
        int icon = R.drawable.file_icon_unknown_small;
        if ("rvt".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_rvt_small;
        } else if ("dwg".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_dwg_small;
        } else if ("pdf".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_pdf_small;
        } else if ("jpg".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_jpg_small;
        } else if ("png".equalsIgnoreCase(subfix)) {
            icon = R.drawable.file_icon_png_small;
        }
        return icon;
    }

    /**
     * 获取ip地址
     * @return
     */
    public static String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;

    }

    public static int getStatusBarHeight() {
        int statusBarHeight2 = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight2 = TjadApplication.getInstance().getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight2;
    }

    public static String getFormatTime(long time, String format) {
        DateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(new Date(time));
    }

    public static List<Integer> getIds(List<Serializable> itemList) {
        if (itemList == null) {
            return null;
        }
        List<Integer> idList = new ArrayList<>();
        for (Serializable item : itemList) {
            try {
                Field field = item.getClass().getField("id");
                field.setAccessible(true);
                int id = field.getInt(item);
                idList.add(id);
            } catch (Exception e) {

            }
        }
        return idList;
    }

    public static String getConsStatusByCode(int statusCode) {
        String status = "";
        if (statusCode == 0) {
            status = " 草稿 ";
        } else if (statusCode == 1) {
            status = "进行中";
        } else if (statusCode == 2) {
            status = "已完成";
        } else if (statusCode == 3) {
            status = "已作废";
        }
        return status;
    }

    public static int getDesignStatusBackground(int statusCode) {
        int background = R.color.transparent;
        if (statusCode == 0) {
            background = R.drawable.design_status_draft;
        } else if (statusCode == 1){
            background = R.drawable.design_status_doing;
        } else if (statusCode == 2) {
            background = R.drawable.design_status_finished;
        }
        return background;
    }

    public static int getConsStatusIconId(int statusCode) {
        int iconId = 0;
        if (statusCode == 0) {
            iconId = R.drawable.construction_status_doing;
        } else if (statusCode == 1) {
            iconId = R.drawable.construction_status_doing;
        } else if (statusCode == 2) {
            iconId = R.drawable.construction_status_doing;
        } else if (statusCode == 3) {
            iconId = R.drawable.construction_status_doing;
        }
        return iconId;
    }

    public static String getDesignPriority(int code) {
        String priority = "一般";
        switch (code) {
            case 0:
                priority = "紧急";
                break;
            case 1:
                priority = "一般";
                break;
            case 2:
                priority = "暂停";
                break;
        }
        return priority;
    }

    public static int getPriorityColor(int priority) {
        int color = AppUtils.getColor(R.color.design_priority_normal);
        if (priority == 0) {
            color = AppUtils.getColor(R.color.design_priority_emergency);
        } else if (priority == 1) {
            color = AppUtils.getColor(R.color.design_priority_normal);
        } else if (priority == 2) {
            color = AppUtils.getColor(R.color.design_priority_suspend);
        }
        return color;
    }

    public static String getTaskStatus(int statusCode) {
        String status = "";
        if (statusCode == 0) {
            status = "未开始";
        } else if (statusCode == 1) {
            status = "进行中";
        } else if (statusCode == 2) {
            status = "已完成";
        }
        return status;
    }

    public static int getTaskStatusDrawable(int statusCode) {
        int status = R.drawable.plan_task_status_not_start;
        if (statusCode == 0) {
            status = R.drawable.plan_task_status_not_start;
        } else if (statusCode == 1) {
            status = R.drawable.plan_task_status_inprogress;
        } else if (statusCode == 2) {
            status = R.drawable.plan_task_status_finished;
        }
        return status;
    }


    public static String imageToBase64(String imagePath) {
        InputStream is = null;
        byte[] data = null;
        try {
            is = new FileInputStream(imagePath);
            data = new byte[is.available()];
            is.read(data);
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encode(data, Base64.DEFAULT));
    }

    public static void asnycImageToBase64(final List<String> imageList, final IImageToStringCallback callback) {
        if (imageList == null || imageList.size() == 0) {
            return;
        }
        final Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        int index = msg.arg1;
                        if (callback != null) {
                            callback.onProgress(index);
                        }
                        break;
                    case 1:
                        List<String> imageData = (List<String>) msg.obj;
                        if (callback != null) {
                            callback.onFinish(imageData);
                        }
                        break;
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<String> imageData = new ArrayList<String>();
                for (int i = 0; i < imageList.size(); i++) {
                    Message message = Message.obtain();
                    message.what = 0;
                    message.arg1 = i;
                    handler.sendMessage(message);
                    String data = imageToBase64(imageList.get(i));
                    imageData.add(data);
                }
                Message message = Message.obtain();
                message.what = 1;
                message.obj = imageData;
                handler.sendMessage(message);
            }
        }).start();
    }

    public static View createEmptyView(Context context) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.empty_view_layout, null, false);
        return view;
    }

    public static int[] getScreenSize(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            windowManager.getDefaultDisplay().getRealMetrics(dm);
        } else {
            windowManager.getDefaultDisplay().getMetrics(dm);
        }
        return new int[] {dm.widthPixels, dm.heightPixels};
    }

    public static int getVersionCode() {
        PackageManager pm = TjadApplication.getInstance().getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(TjadApplication.getInstance().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (pi != null) {
            return pi.versionCode;
        }
        return -1;
    }

    public static boolean isAppUpdate() {
        SPCacheManager cacheManager = TjadApplication.getInstance().getSpCacheManager();
        int currentVersion = getVersionCode();
        int storedVersion = cacheManager.getInt("appVersionCode", -1);
        return currentVersion != storedVersion;
    }

    public static void recordAppVersionCode() {
        SPCacheManager cacheManager = TjadApplication.getInstance().getSpCacheManager();
        int currentVersion = getVersionCode();
        cacheManager.putInt("appVersionCode", currentVersion);
    }

    public static String addVersionToFileName(String fileName, String version) {
        String newFile;
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1) {
            newFile = fileName + "-v" + version;
        } else {
            String name = fileName.substring(0, dotIndex);
            String subfix = fileName.substring(dotIndex + 1);
            newFile = name + "-v" + version + "." + subfix;
        }
        return newFile;

    }

    public static String getFormStatus(int id) {
        if (id == 0) {
            return "草稿";
        } else if (id == 1) {
            return "进行中";
        } else if (id == 2) {
            return "完成";
        }
        return "草稿";
    }

    public static int getFormStatusBackgroundRes(int id) {
        if (id == 0) {
            return R.drawable.design_status_draft;
        } else if (id == 1) {
            return R.drawable.design_status_doing;
        } else if (id == 2) {
            return R.drawable.design_status_finished;
        }
        return R.drawable.design_status_draft;
    }

}
